<?php
/**
 * Created by PhpStorm.
 * User: cen
 * Date: 2020/6/8
 * Time: 22:33
 */

namespace app\index\controller;


use think\Controller;
use app\index\model\UserModel;
use think\Exception;
use think\facade\Session;


class User extends Controller
{
    /**
     * 用户登录页面
     * @return mixed
     */
    public function login(){
        return $this->fetch();
    }

    /**
     * 用户注册页面
     * @return mixed
     */
    public function register(){
        return $this->fetch();
    }

    /**
     * 用户登录提交
     * @return \think\response\Json
     */
    public function submitLogin(){
        try{
            $data = $this->request->param();
            $result = $this->validate($data,'app\index\validate\User.login');
            if (true !== $result) {
                // 验证失败 输出错误信息
                throw new Exception($result);
            }
            $res = UserModel::where('username', $data['username'])->find();
            if($res === null){
                throw new Exception('用户或密码错误');
            }

            if(password_verify($data['password'],$res->password) === false){
                throw new Exception('用户或密码错误');
            }

            //session_start();
            //Session::start();
            //$sid = session_id();
            //cookie('indexSid',$sid);
            //cookie('username',$res['username']);

            //Session::set($sid,$res->toArray());
            //Session::set('dd','ffff');


            $res = $res->toArray();
            unset($res['password']);


            return json($res);
        }catch (\Exception $e){
            return json($e->getMessage(),401);
        }
    }

    /**
     * 用户注册提交
     * @return \think\response\Json
     */
    public function submitRegister(){
        try{
            $data = $this->request->param();
            $result = $this->validate($data,'app\index\validate\User.register');
            if (true !== $result) {
                // 验证失败 输出错误信息
                throw new Exception($result);
            }
            $res = UserModel::where('username', $data['username'])->find();
            if($res !== null){
                throw new Exception('该用户已注册');
            }

            $passwordHash = password_hash($data['password'],PASSWORD_DEFAULT);

            if($passwordHash === false){
                throw new Exception('password hash failed');
            }

            UserModel::create([
                'username' => $data['username'],
                'password' => $passwordHash]
            );

            return json('success');
        }catch (\Exception $e){
            return json($e->getMessage(),401);
        }
    }


}